<?php

namespace Plugins\AdminBasic\Http\Admin\Service;

use App\Util\EasySearchMacro\GlobalSearch;
use App\Util\Password;
use Plugins\AdminBasic\Models\BasicRole;
use Sc\Util\ImitateAopProxy\AopProxyTrait;
use App\Http\Admin\Service\Traits\DestroyServiceTrait;
use App\Http\Admin\Service\Traits\StoreServiceTrait;
use App\Http\Admin\Service\Traits\SwitchServiceTrait;
use App\Http\Admin\Service\Traits\UpdateServiceTrait;
use App\Util\EasySearch;
use Plugins\AdminBasic\Models\BasicAdministrators;


/**
 * 管理员
 */
class AdministratorsService
{

    use AopProxyTrait;
    use StoreServiceTrait;
    use UpdateServiceTrait;
    use DestroyServiceTrait;
    use SwitchServiceTrait;

    /**
     * 获取模型
     */
    public function getModel(int $id = null): BasicAdministrators
    {
        return $id ? BasicAdministrators::find($id) :new BasicAdministrators();
    }

    public function beforeStore(&$data): void
    {
        $data['password'] = Password::get($data['password']);
    }

    public function beforeUpdate(&$data, BasicAdministrators $model): void
    {
        unset($data['password']);
    }

    /**
     * @return array
     */
    public function lists(): array
    {
        $query   = BasicAdministrators::select([
            'id',
            'name',
            'account',
            'lately_time',
            'status',
            'role_ids',
            'create_time',
        ])->where('id', '>', 1);

        $data    = EasySearch::create($query)->addMacro(GlobalSearch::class, 'name', 'account',)->getData();
        $roleIds = array_unique(array_merge(...$data['data']->pluck('role_ids')->toArray()));
        $roleMap = BasicRole::whereIn('id', $roleIds)->pluck('name', 'id');

        $data['data']->map(function ($value) use ($roleMap) {
            $value['role'] = implode(',', array_map(fn($v) => $roleMap[$v] ?? '-', $value['role_ids']));
        });

        return $data;
    }

    /**
     * 重置密码
     *
     * @param mixed $id
     *
     * @return void
     */
    public function reseatPassword(mixed $id): void
    {
        $administrators           = BasicAdministrators::find($id);
        $administrators->password = password_hash('123456', PASSWORD_DEFAULT);
        $administrators->save();
    }
}